package com.chrissy.music.framework.filter;

import cn.hutool.core.text.CharSequenceUtil;
import com.chrissy.music.common.cache.TokenStoreCache;
import com.chrissy.music.common.entity.LoginUser;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @author Johnson
 */
@Component
@RequiredArgsConstructor
public class AuthenticationTokenFilter extends OncePerRequestFilter {

    private final TokenStoreCache tokenStoreCache;

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain filterChain) throws ServletException, IOException {
        String accessToken = request.getHeader("Authorization");
        if (CharSequenceUtil.isBlank(accessToken)) {
            accessToken = request.getParameter("access_token");
        }
        if (StringUtils.isBlank(accessToken)) {
            filterChain.doFilter(request, response);
            return;
        }
        // 获取登录用户信息
        LoginUser user = tokenStoreCache.getUser(accessToken);
        if (user == null) {
            filterChain.doFilter(request, response);
            return;
        }
        // 用户存在
        Authentication authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());

        // 新建 SecurityContext
        SecurityContext context = SecurityContextHolder.createEmptyContext();
        context.setAuthentication(authentication);
        SecurityContextHolder.setContext(context);

        filterChain.doFilter(request, response);
    }
}
